package com.ztools.pc.service.impl.card;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ztools.common.model.pc.card.CardMaster;
import com.ztools.common.model.pc.export.CardMasterExport;
import com.ztools.common.model.pc.information.WeChatMember;
import com.ztools.common.util.common.PageUtil;
import com.ztools.common.util.pc.DictUtil;
import com.ztools.common.util.pc.RedisUtil;
import com.ztools.pc.mapper.card.CardMasterMapper;
import com.ztools.pc.service.card.CardMasterService;
import com.ztools.pc.service.information.MemberService;
import com.ztools.pc.service.sys.DictService;
import com.ztools.pc.util.ExcelUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author seeTools
 * @since 2023-06-26
 */
@Service
public class CardMasterServiceImpl extends ServiceImpl<CardMasterMapper, CardMaster> implements CardMasterService {

    public final static String CARD_DEFAULT_PWD = "888888";
    protected Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private ExcelUtil excelUtil;
    @Resource
    private DictService dictService;
    @Resource
    private MemberService memberService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 分页查询
     *
     * @param pageUtil 分页数据
     * @return 对象
     */
    @Override
    public Page<CardMaster> findList(PageUtil<CardMaster> pageUtil) {
        List<OrderItem> orders = new ArrayList<>();
        QueryWrapper<CardMaster> queryWrapper = getQueryWrapper(pageUtil.getParams());
        Page<CardMaster> pages = new Page<>(pageUtil.getPage(), pageUtil.getSize());
        // 排序数据  StrUtil.toUnderlineCase huTools将驼峰装换为下划线格式
        orders.add(new OrderItem(StrUtil.toUnderlineCase(pageUtil.getSortName()), "asc".equals(pageUtil.getSortOrder())));
        pages.setOrders(orders);
        Page<CardMaster> page = page(pages, queryWrapper);
        dictionary(page.getRecords());
        return page;
    }

    @Override
    public List<CardMaster> findByObject(CardMaster cardMaster) {
        QueryWrapper<CardMaster> queryWrapper = new QueryWrapper<>(cardMaster);
        List<CardMaster> list = list(queryWrapper);
        dictionary(list);
        return list;
    }

    @Override
    public boolean update(CardMaster cardMaster) {
        boolean b = false;
        // 修改前先获取，在删除（乐观锁）
        CardMaster byId = getById(cardMaster);
        b = updateById(cardMaster);
        return b;
    }

    @Override
    public boolean delete(CardMaster cardMaster) {
        boolean b = false;
        CardMaster byId = getById(cardMaster);
        b = removeById(cardMaster);
        return b;
    }

    public QueryWrapper<CardMaster> getQueryWrapper(CardMaster cardMaster) {
        QueryWrapper<CardMaster> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(cardMaster.getUid())) {
            queryWrapper.lambda().eq(CardMaster::getUid, cardMaster.getUid());
        }
        if (StrUtil.isNotEmpty(cardMaster.getCardNo())) {
            queryWrapper.lambda().eq(CardMaster::getCardNo, cardMaster.getCardNo());
        }
        if (cardMaster.getCardType() != null) {
            queryWrapper.lambda().eq(CardMaster::getCardType, cardMaster.getCardType());
        }
        if (cardMaster.getCardStatus() != null) {
            queryWrapper.lambda().eq(CardMaster::getCardStatus, cardMaster.getCardStatus());
        }
        if (StrUtil.isNotEmpty(cardMaster.getCardName())) {
            queryWrapper.lambda().like(CardMaster::getCardName, cardMaster.getCardName());
        }
        if (cardMaster.getMemberId() != null) {
            queryWrapper.lambda().eq(CardMaster::getMemberId, cardMaster.getMemberId());
        }
        if (StrUtil.isNotEmpty(cardMaster.getMemberPhone())) {
            queryWrapper.lambda().eq(CardMaster::getMemberPhone, cardMaster.getMemberPhone());
        }
        if (cardMaster.getBalanceMin() != null) {
            queryWrapper.lambda().le(CardMaster::getBalance, cardMaster.getBalanceMin());
        }
        if (cardMaster.getBalanceMax() != null) {
            queryWrapper.lambda().gt(CardMaster::getBalance, cardMaster.getBalanceMax());
        }
        if (cardMaster.getBuildStartDate() != null) {
            queryWrapper.lambda().lt(CardMaster::getBuildDate, cardMaster.getBuildStartDate());
        }
        if (cardMaster.getBuildEndDate() != null) {
            queryWrapper.lambda().ge(CardMaster::getBuildDate, cardMaster.getBuildEndDate());
        }
        if (StrUtil.isNotEmpty(cardMaster.getMemberPhone())) {
            queryWrapper.lambda().like(CardMaster::getMemberPhone, cardMaster.getMemberPhone());
        }
        return queryWrapper;
    }

    /**
     * 字典翻译
     *
     * @param cardMasterList 对象集合
     */
    public void dictionary(List<CardMaster> cardMasterList) {
        for (CardMaster cardMaster : cardMasterList) {
            dictionary(cardMaster);
        }
    }

    public void dictionary(CardMaster cardMaster) {
        if (cardMaster != null) {
            if (cardMaster.getCardType() != null) {
                cardMaster.setCardTypeName(dictService.findByTypeCode(DictUtil.CARD_TYPE, cardMaster.getCardType() + ""));
            }
            if (cardMaster.getCardStatus() != null) {
                cardMaster.setCardStatusName(dictService.findByTypeCode(DictUtil.CARD_STATUS, cardMaster.getCardStatus() + ""));
            }
        }
    }

    @Override
    public void exportExcel(HttpServletResponse response, CardMaster cardMaster) {
        long count = count();
        long sheetNumber = ExcelUtil.SHEET_NUMBER;
        long pageSize = excelUtil.getPageSize(sheetNumber, count);
        QueryWrapper<CardMaster> queryWrapper = new QueryWrapper<>(cardMaster);
        for (int i = 0; i < pageSize; i++) {
            Page<CardMaster> pages = new Page<>(i, sheetNumber);
            Page<CardMaster> page = page(pages, queryWrapper);
            List<CardMaster> list = page.getRecords();
            dictionary(list);
            excelUtil.exportExcel(response, i, list, CardMasterExport.class, "主卡基本信息");
        }
    }

    @Override
    public List<CardMaster> getCardList(Long memberId) {
        QueryWrapper<CardMaster> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CardMaster::getCardStatus, 0)
                .eq(CardMaster::getMemberId, memberId);
        List<CardMaster> list = list(queryWrapper);
        dictionary(list);
        return list;
    }

    @Override
    public CardMaster getCardInfoByNo(String cardNo) {
        LambdaQueryWrapper<CardMaster> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CardMaster::getCardNo, cardNo);
        CardMaster cardMaster = getOne(queryWrapper);
        dictionary(cardMaster);
        return cardMaster;
    }

    @Override
    public boolean openCard(Long memberId) {
        WeChatMember member = memberService.getById(memberId);
        String uuid = IdUtil.simpleUUID();
        Date date = new Date();
        String cardNo = getCardNo();
        CardMaster cardMaster = CardMaster.builder()
                .uid(uuid)
                .cardNo(cardNo)
                .cardType(0)
                .cardStatus(0)
                .cardName(member.getNickName() + "的储值卡")
                .buildDate(date)
                .memberId(memberId)
                .memberPhone(member.getPhone())
                .password(DigestUtil.md5Hex(CARD_DEFAULT_PWD))
                .remark("公众号开卡")
                .build();
        return save(cardMaster);
    }


    @Override
    public String getCardNo() {
        // 卡前缀
        String prefix = "7";
        // 储值卡卡号长度为9
        int cardNoLength = 9;
        Long number = stringRedisTemplate.opsForValue().increment(RedisUtil.DATA_CARD_NO_NUMBER);
        return StrUtil.padAfter(prefix, cardNoLength - (number + "").length(), "0") + number;
    }


}

